package com.adtech.adms.commons.web.intercepter;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.adtech.adms.commons.util.SqlValidate;
import com.adtech.core.Settings;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

/**
 * 
 * 
 * @author Dormin 
 * @since 2012-2-3 
 * 
 * @Copyright (C) AD Tech Workshop All Right Reserved
 */
public class SafeInterceptor extends
		org.apache.struts2.interceptor.TokenInterceptor {

	private static final long serialVersionUID = -3155760331125228568L;

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		ActionContext  context =  invocation.getInvocationContext();
	
		
		
		if("true".equals(Settings.get("save.validateparams"))){	
		//2 获取所有方法
		HttpServletRequest request = ServletActionContext.getRequest();		
		Object actionObj= invocation.getAction();
		@SuppressWarnings("unused")
		Method[] methods = actionObj.getClass().getMethods();
		//3 Post处理
		Map<?, ?> postmap = request.getParameterMap();	
		
		if (postmap.containsKey("tdqssid")) {
			 String usid = request.getParameter("tdqssid");
			 String sid = request.getSession().getId();
			 if(!sid.equals(usid)){
				 return "securityexceptionerror";				 
			 }
		} 
		
		Set<?> keySet = postmap.keySet();
		for (Iterator<?> it = keySet.iterator(); it.hasNext();) {
			String fieldName = it.next().toString();
			String fildValue = request.getParameter(fieldName);				
			//SQL验证
			if(!SqlValidate.validate(fildValue))
			{
				return "securityexceptionerror";
			}
		}	
		}
		return	handleValidToken(invocation);
	}

}
